import React, { useEffect } from 'react';
import gsap from 'gsap';

interface UploadProps {
  onImageUpload?: (imageUrl: string | null, file?: File) => void;
  uploadedImage?: string | null;
  label: string;
  isReference?: boolean;
  onEdit?: (imageUrl: string) => void; // 新增编辑回调
}

const ImageUpload: React.FC<UploadProps & { 
  uploadRef: React.RefObject<HTMLDivElement | null>;
  currentImagePreview: string | null;
  onUploadClick: () => void;
}> = ({ 
  onImageUpload, 
  uploadedImage, 
  label, 
  isReference = false,
  uploadRef,
  currentImagePreview,
  onUploadClick,
  onEdit
}) => {
  const currentPreview = uploadedImage || currentImagePreview || null;

  // 悬停动画
  useEffect(() => {
    if (!uploadRef.current) return;
    
    const containerElement = uploadRef.current;
    const tileElement = containerElement?.querySelector(".upload-tile");

    if (containerElement && tileElement) {
      let isHovered = false;
      let animationTween: gsap.core.Tween | null = null;

      const handleMouseEnter = () => {
        if (isHovered) return;
        isHovered = true;

        // 停止之前的动画
        if (animationTween) {
          animationTween.kill();
        }

        // 根据是否有图片预览来决定动画效果
        if (currentPreview) {
          // 有图片时：轻微放大
          animationTween = gsap.to(tileElement, {
            rotationZ: isReference ? 8 : -8, // 参考图反向倾斜
            scale: 1.05, // 轻微放大
            duration: 0.3,
            ease: "power2.out",
          });
        } else {
          // 无图片时：放大效果
          animationTween = gsap.to(tileElement, {
            rotationZ: isReference ? 8 : -8, // 参考图反向倾斜
            scale: 1.15,
            duration: 0.3,
            ease: "power2.out",
          });
        }
      };

      const handleMouseLeave = () => {
        if (!isHovered) return;
        isHovered = false;

        // 停止之前的动画
        if (animationTween) {
          animationTween.kill();
        }

        // 根据是否有图片预览来决定恢复动画
        if (currentPreview) {
          // 有图片时：恢复轻微放大
          animationTween = gsap.to(tileElement, {
            rotationZ: isReference ? 8 : -8, // 参考图反向倾斜
            scale: 1, // 恢复原始大小
            duration: 0.3,
            ease: "power2.out",
          });
        } else {
          // 无图片时：恢复放大效果
          animationTween = gsap.to(tileElement, {
            rotationZ: isReference ? 8 : -8, // 参考图反向倾斜
            scale: 1,
            duration: 0.3,
            ease: "power2.out",
          });
        }
      };

      // 容器监听事件，内部元素执行动画
      containerElement.addEventListener("mouseenter", handleMouseEnter);
      containerElement.addEventListener("mouseleave", handleMouseLeave);

      return () => {
        containerElement.removeEventListener("mouseenter", handleMouseEnter);
        containerElement.removeEventListener("mouseleave", handleMouseLeave);
        if (animationTween) {
          animationTween.kill();
        }
      };
    }
  }, [currentPreview, isReference, uploadRef]);

  return (
    <div
      className="upload-container"
      ref={uploadRef}
      onClick={onUploadClick}
    >
      <div className="upload-tile">
        {currentPreview ? (
          <div className="uploaded-image">
            <img
              src={currentPreview}
              alt={label}
              className="preview-image"
              onLoad={() => {}}
              onError={() => {}}
            />
            <div className="upload-actions" onClick={(e) => e.stopPropagation()}>
              <button
                className="upload-action"
                onClick={(e) => {
                  e.stopPropagation();
                  if (currentPreview && onEdit) {
                    onEdit(currentPreview);
                  } else {
                    onUploadClick();
                  }
                }}
                title="编辑"
              >
                编辑
              </button>
              <span className="upload-action-sep">|</span>
              <button
                className="upload-action delete"
                onClick={(e) => {
                  e.stopPropagation();
                  onImageUpload?.(null);
                }}
                title="删除"
              >
                删除
              </button>
            </div>
          </div>
        ) : (
          <>
            <div className="upload-plus">+</div>
            <div className="upload-label">{label}</div>
          </>
        )}
      </div>
    </div>
  );
};

export default ImageUpload;
